package com.java.multipledatasource.thread;

/**
 * @author hu
 * @version 1.0
 * @date 2021/1/19 0019 上午 9:43
 * @description
 */
public class Alternately {

    static volatile boolean FLAG = true;

    static int COUNT = 0;

    final static Object OBJ = new Object();

    public static void main(String[] args) {
        new Thread(() -> {
         synchronized (OBJ) {
             while (true) {
                if (FLAG) {
                    System.out.println(Thread.currentThread().getName() + " " + ++COUNT);
                    try {
                        OBJ.wait();
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    FLAG = true;
                    OBJ.notify();
                }
             }
         }
        }, "t1").start();

        new Thread(() -> {
            synchronized (OBJ) {
                while (true) {
                    if (!FLAG) {
                        System.out.println(Thread.currentThread().getName() + " " + ++COUNT);

                        try {
                            OBJ.wait();
                            Thread.sleep(1000);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        FLAG = false;
                        OBJ.notify();
                    }
                }
            }
        }, "t2").start();
    }
}
